let _vue = null;
export default class VueRouter {
  static install(Vue) {
    //判断当前插件是否安装
    if (VueRouter.install.installed) {
      //静态方法使用vuerouter.install
      return;
    }
    VueRouter.install.installed = true;
    //把vue构造函数记录全局变量
    _vue = Vue;
    console.log(_vue);
    //把创建的vue实例 的时候传入的router的对象注入到vue实例上
    //混入
    _vue.mixin({
      beforeCreate() {
        if (this.$options.$router) {
          _vue.prototype.$router = this.$options.$router;
          this.$options.router.init();
        }
      },
    });
  }
  constructor(options) {
    this.options = options;
    this.routerMap = {};
    console.log(_vue);
    this.data = _vue.observable({
      //vue响应式
      current: "/",
    });
  }
  init() {
    this.createRouterMap();
    this.initComponents(_vue);
  }
  createRouterMap() {
    //遍历所有的路由规则把所有规则解析成键值对的形式 存储到routeMap中
    this.options.routes.forEach((route) => {
      this.routerMap[route.path] = route.component;1
    });
  }
  initComponent(Vue) {
    Vue.component("router-link", {
      props: {
        to: String,
      },
      render(h) {
        return h(
          "a",
          {
            attrs: {
              href: this.to,
            },
            on: {
              click: this.clickhander,
            },
          },
          [this.$slots.default]
        );
      },
      methods: {
        clickhander(e) {
          history.pushState({}, "", this.to);
          this.$router.data.current = this.to;
          e.preventDefault();
        },
      },
      // template:"<a :href='to'><slot></slot><>"
    });
    const self = this;
    Vue.component("router-view", {
      render(h) {
        // self.data.current
        const cm = self.routeMap[self.data.current];
        return h(cm);
      },
    });
  }
  initEvent() {
    window.addEventListener("popstate", () => {
      this.data.current = window.location.pathname;
    });
  }
}
